<?php

namespace App\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class TrendsComment extends BaseModel
{
    protected $table = 'trends_comment';
    private $fields = ['comment_id', 'content_id', 'user_id', 'comment_text', 'create_timestamp', 'comment_img'];


    public function getList($input = [])
    {
        $where = $input['content_id'] ?? 0;
        $whereReply = $input['content_id'] ?? 0;
        if (isset($input['seachTime'])) {
            $min = strtotime($input['seachTime'][0]) ?? 0;
            $max = strtotime($input['seachTime'][1]) ?? 0;
            $where .= " AND b.create_timestamp > $min AND b.create_timestamp < $max ";
            $whereReply .= " AND create_timestamp > $min AND create_timestamp < $max ";
        }
        $limit = $input['limit'] ?: 10;
        $page = $input['page'] ?: 1;
        if (isset($input['uuid'])) $where .= " AND uuid = " . $input['uuid'];
        $sql = "
         select nickname,uuid,b.comment_id,b.user_id, COALESCE(all_reply_ids,0) as all_reply_ids,b.comment_text,b.create_timestamp
         from zb_trends_content a left join zb_trends_comment b on a.content_id = b.content_id
         left join zb_user u on b.user_id = u.user_id
         left join (select comment_id,count(id) as all_reply_ids from zb_trends_reply where content_id = $whereReply group by comment_id ) c on c.comment_id = b.comment_id
         where a.content_id = $where group by b.comment_id;
        ";
        $data = DB::connection('api')->select($sql);
        $like_sql = "select count(id) as count_like from zb_trends_content_like where content_id = $whereReply AND is_cancel = 0";
        $like_data = DB::connection('api')->select($like_sql);

        if (!empty($data) && is_null($data[0]->user_id)) {
            $data = [];
        }
        $total = count($data);
        $content_num = array_sum(array_column($data, 'all_reply_ids')) + $total;
        $data = collect($data)->forPage($page, $limit)->values()->toArray();
        return ['total' => $total, 'data' => $data, 'trends_num' => $content_num, 'like_num' => $like_data[0]->count_like, 'current_page' => intval($page)];
    }

    public function deleteComment($comment_id)
    {
        $data['comment_id'] = $comment_id;
        return curl_request(getKkaudioApiUrl() . '/inner/trends/comment/del', $data, 'urlencoded', 'GET');
    }


}
